package rabbitmq.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

// 工作队列模式
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 设置属性
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        // 2. 开启信道
        Channel channel = connection.createChannel();

        // 3. 生产者需要声明交换机
        // 4. 声明队列
        channel.queueDeclare(Constants.WORK_QUEUE, false, false, false, null);

        // 5. 发送消息
        for (int i = 0; i < 10; i++) {
            String meg = "hello work queue..." +i;
            channel.basicPublish("", Constants.WORK_QUEUE, null,meg.getBytes());
        }
        System.out.println("消息发送成功");

        // 6. 进行资源的释放
        channel.close();
        connection.close();
    }
}
